//
//  BIZConsultEditViewController.m
//  biz
//
//  Created by 边文辉 on 2017/3/17.
//  Copyright © 2017年 jieshuibao. All rights reserved.
//

#import "BIZConsultEditViewController.h"
#import "TZImagePickerController.h"
#import "BrowserView.h"
#import "BWHTextView.h"
#import "BIZConsultQModel.h"
#import "BIZConsultRecordsVC.h"

@interface BIZConsultEditViewController ()<TZImagePickerControllerDelegate,
                                          UIScrollViewDelegate>
{
    NSMutableArray *_selectedPhotos;
    NSMutableArray *_selectedAssets;
}
@property (weak, nonatomic) IBOutlet BWHTextView *inputTextView;
@property (weak, nonatomic) IBOutlet UILabel *imageCountLabel;
@property (weak, nonatomic) IBOutlet UIButton *first;
@property (weak, nonatomic) IBOutlet UIButton *second;
@property (weak, nonatomic) IBOutlet UIButton *third;
//@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIButton *twoHourBtn;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *twoHourBtnHeightLayout;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *spaceHeightLayout;
@property (weak, nonatomic) IBOutlet UIButton *oneDayBtn;
/** <#assign属性注释#> */
@property (nonatomic, assign) NSInteger timeBtnTagSelected;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *spaceViewTopLayout;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *onedayBtnHeightLayout;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *spaceBottomLayout;
@property (weak, nonatomic) IBOutlet UILabel *regulationLabel;
@property (nonatomic, strong) UIButton *rightBtn;

@end

@implementation BIZConsultEditViewController

- (instancetype)initWithType:(BIZConsultEditType)type cuserId:(NSString *)cuserId finishBlock:(BIZConsultEditFinishBlock)finishBlock
{
    self = [super init];
    if (self) {
        _type = type;
        _finishBlock = finishBlock;
        
        if (cuserId) {
            _cuserId = [cuserId copy];
        }
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"问题咨询";
//    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon-denglu-fanhui副本"] style:UIBarButtonItemStyleDone target:self action:@selector(leftBarButtonItemDidClicked:)];
    
    self.rightBtn = [[UIButton alloc]init];
    float rightBtnWidth = [NSString widthForString:@"咨询记录" fontSize:16 andHeight:44];
    self.rightBtn.frame = CGRectMake(0, 0, rightBtnWidth, 17);
    self.rightBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    [self.rightBtn setTitle:@"咨询记录" forState:UIControlStateNormal];
    [self.rightBtn setTintColor:[UIColor whiteColor]];
    [self.rightBtn addTarget:self action:@selector(rightBarButtonItemDidClicked:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:self.rightBtn];
    
    self.inputTextView.placeHolder = @"请详细描述您的问题，可附上图片......";
    
    [self setupBtnGas];
    
    self.timeBtnTagSelected = 0;
    
    if (self.type == BIZConsultEditTypeOne2One) {
        [self.oneDayBtn setTitleColor:HEXCOLOR(0x2E8CE5) forState:UIControlStateNormal];
        self.oneDayBtn.layer.borderColor = HEXCOLOR(0x2E8CE5).CGColor;
        [self.twoHourBtn setTitleColor:HEXCOLOR(0x999999) forState:UIControlStateNormal];
        self.twoHourBtn.layer.borderColor = HEXCOLOR(0x999999).CGColor;
        self.regulationLabel.text = @"24小时内接单：您的问题在发布的24小时内会有咨询师回答，如果在24小时内咨询师没有回答，则咨询次数不会被扣除。";
    }
    
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self getTabBarRedBadgeData];
}

- (void)getTabBarRedBadgeData {

    
    [RequestTool POST:kTabBarRedBadgeUrl parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        DeLog(@"kTabBarRedStatusURL---responseObject %@", responseObject);
//        [MBProgressHUD hideHUD];
        if ([responseObject[@"code"] integerValue] == 1) {
   
            
            if (([responseObject[@"data"][@"oneRed"] integerValue])
                ||([responseObject[@"data"][@"rapidRed"]  integerValue])) {
                [self.tabBarController.tabBar.items[0] showBadge];
                
            } else {
                [self.tabBarController.tabBar.items[0] hidenBadge];
            }
            
            
            if ([responseObject[@"data"][@"officialCount"] integerValue]){
               [self.rightBtn showBadge];
            } else {
                 [self.rightBtn hidenBadge];
            }

        }
        else {
//                        [MBProgressHUD showInfoMessage:responseObject[@"des"]];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        DeLog(@"error %@", error);
//        [MBProgressHUD hideHUD];
//                if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
//                    [MBProgressHUD showErrorMessage:@"网络不给力"];
//                }
//                else {
//                    [MBProgressHUD showErrorMessage:@"服务器繁忙"];
//                }
    }];
}

-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    if (self.type != BIZConsultEditTypeOne2One) {
//        self.twoHourBtnHeightLayout.constant = 0;
//        self.spaceHeightLayout.constant = 0;
        self.spaceViewTopLayout.constant = 0;
//        self.onedayBtnHeightLayout.constant = 0;
        self.spaceBottomLayout.constant = 0;
        self.oneDayBtn.hidden = YES;
        self.twoHourBtn.hidden = YES;
    }
}

- (void)leftBarButtonItemDidClicked:(UIBarButtonItem *)left
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)rightBarButtonItemDidClicked:(UIBarButtonItem *)barButtonItem {
    BIZConsultRecordsVC *history = [BIZConsultRecordsVC viewControllerFromStoryboard];
    [self.navigationController pushViewController:history animated:YES];
}


- (NSArray *)subImages
{
    NSMutableArray *res = [@[] mutableCopy];
    
    NSArray *arr = @[_first, _second, _third];
    
    for (UIButton *btn in arr) {
        if (btn.currentImage) {
            [res addObject:[btn.currentImage image2Base64StringWithMaxDataSize:1024 * 200 maxSize:CGSizeMake(50, 50)]];
        }
    }
    
    return [res copy];
}


- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.view endEditing:YES];
}

#pragma mark - 选取照片

- (IBAction)addPicture:(UIButton *)sender {
    
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:3 delegate:self];
    
    imagePickerVc.allowTakePicture = YES;
    imagePickerVc.allowPickingOriginalPhoto = NO;
    imagePickerVc.allowPickingVideo = NO;
    imagePickerVc.sortAscendingByModificationDate = YES;
    imagePickerVc.alwaysEnableDoneBtn = YES;
    imagePickerVc.selectedAssets = _selectedAssets;
    
    [self presentViewController:imagePickerVc animated:YES completion:nil];
    
}

- (void)imagePickerController:(TZImagePickerController *)picker
       didFinishPickingPhotos:(NSArray *)photos
                 sourceAssets:(NSArray *)assets
        isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto
{
    
    _selectedPhotos = [NSMutableArray arrayWithArray:photos];
    _selectedAssets = [NSMutableArray arrayWithArray:assets];
    
    [self reloadImages];
}


/**
 移除
 */
- (IBAction)removeImage:(UIButton *)sender {
    
    NSInteger index = -1;
    if (sender == self.first) {
        index = 0;
    } else if (sender == self.second) {
        index = 1;
    } else if (sender == self.third) {
        index = 2;
    }
    
    if (index > -1) {
        [_selectedPhotos removeObjectAtIndex:index];
        [_selectedAssets removeObjectAtIndex:index];
        [self reloadImages];
    }
}



/**
 重新加载图片
 */
- (void)reloadImages
{
    [self setButton:self.third imageWithCount:3 nextBtn:nil];
    [self setButton:self.second imageWithCount:2 nextBtn:self.third];
    [self setButton:self.first imageWithCount:1 nextBtn:self.second];
    
    self.imageCountLabel.text = [NSString stringWithFormat:@"(%lu/3)", (unsigned long)_selectedAssets.count];
}


- (void)setButton:(UIButton *)btn imageWithCount:(NSInteger)count nextBtn:(UIButton *)nextBtn
{
    UIImage *img = (_selectedPhotos.count >= count) ? _selectedPhotos[count - 1] : nil;
    
    [btn setImage:img forState:UIControlStateNormal];
    if (img) {
        btn.hidden = NO;
        nextBtn.hidden = NO;
    } else {
        nextBtn.hidden = YES;
    }
}


- (void)setupBtnGas
{
    [self addGestureRecognizerToView:self.first];
    [self addGestureRecognizerToView:self.second];
    [self addGestureRecognizerToView:self.third];
}


// 添加所有的手势
- (void)addGestureRecognizerToView:(UIView *)view
{
    
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(handleLongPressed:)];
    [view addGestureRecognizer:longPress];
    
    // 点击事件
    [view addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)]];
}



// 长按手势
- (void)handleLongPressed:(UILongPressGestureRecognizer *)longPress
{
    if (longPress.state == UIGestureRecognizerStateBegan) {
        UIButton *btn = (UIButton *)longPress.view;
        if (btn.currentImage) {
            [UIAlertController showAlertViewWithController:self title:@"确认删除" message:nil cancelButtonTitle:@"取消" confirmButtonTitle:@"确认" cancelBlock:nil confirmBlock:^{
                [self removeImage:btn];
            }];
            
        } else {
            [self addPicture:btn];
        }
    }
    
    
}

// 点击手势
- (void)handleTap:(UITapGestureRecognizer *)tap
{
    if (tap.state == UIGestureRecognizerStateRecognized) {
        UIButton *btn = (UIButton *)tap.view;
        
        if (btn.currentImage) {
            [self scaleBtn:btn];
        } else {
            [self addPicture:btn];
        }
    }
}


- (void)scaleBtn:(UIButton *)btn
{
    [BrowserView showImageView:btn];
    
}


- (IBAction)selectTimeBtnClick:(UIButton *)sender {
    
    
    if (sender.tag == 1000) {
        [self.oneDayBtn setTitleColor:HEXCOLOR(0x2E8CE5) forState:UIControlStateNormal];
        self.oneDayBtn.layer.borderColor = HEXCOLOR(0x2E8CE5).CGColor;
        [self.twoHourBtn setTitleColor:HEXCOLOR(0x999999) forState:UIControlStateNormal];
        self.twoHourBtn.layer.borderColor = HEXCOLOR(0x999999).CGColor;
        self.regulationLabel.text = @"24小时内接单：您的问题在发布的24小时内会有咨询师回答，如果在24小时内咨询师没有回答，则咨询次数不会被扣除。";
    }
    else {
        [self.oneDayBtn setTitleColor:HEXCOLOR(0x999999) forState:UIControlStateNormal];
        self.oneDayBtn.layer.borderColor = HEXCOLOR(0x999999).CGColor;
        [self.twoHourBtn setTitleColor:HEXCOLOR(0x2E8CE5) forState:UIControlStateNormal];
        self.twoHourBtn.layer.borderColor = HEXCOLOR(0x2E8CE5).CGColor;
        self.regulationLabel.text = @"2小时内接单：您的问题在发布的2小时内会有咨询师回答，如果在2小时内咨询师没有回答，则咨询次数不会被扣除。";
        
    }
    
    self.timeBtnTagSelected = sender.tag-1000;
    
}

- (IBAction)publicQuestionBtnClick {
    [_inputTextView resignFirstResponder];
    
    if (!self.inputTextView || !self.inputTextView.text.length) {
        [MBProgressHUD showTipMessageInWindow:@"请详细描述您的问题"];
        return;
    }
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[@"question"] = _inputTextView.text;
    
    NSString *url = kOfficialRapidConsultPublishURL;
    
    if (!url || _inputTextView.text.length == 0) return;
    
    NSArray *images = [self subImages];
    if (images.count > 0) {
        dict[@"imgs"] = images;
    }
    
    
//    if (self.type == BIZConsultEditTypeOne2One) {
//        dict[@"type"] = @(self.timeBtnTagSelected);
//    }
    
    
    [MBProgressHUD showAnimationHUD];
    [RequestTool POST:url
           parameters:dict
             progress:nil
              success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                  NSLog(@"response %@", responseObject);
                  
                  int code = [responseObject[@"code"] intValue];
                  if (code == 1) {
                      [MBProgressHUD showSuccessMessage:@"您的问题我们已经收到，请耐心等待" timer:3];
                      
                      MPWeakSelf(self);
                      weakself.inputTextView.text = nil;
                      weakself.inputTextView.placeHolder = @"请详细描述您的问题，可附上图片......";
                      weakself.imageCountLabel.text = @"0/3";
                      _selectedPhotos = [NSMutableArray array];
                      _selectedAssets = [NSMutableArray array];
                      [weakself reloadImages];
//                      dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0/*延迟执行时间*/ * NSEC_PER_SEC));
//                      dispatch_after(delayTime, dispatch_get_main_queue(), ^{
//                          [weakself.navigationController popViewControllerAnimated:YES];
//                      });
//                      BIZConsultQModel *model = [[BIZConsultQModel alloc] init];
//                      model.content = dict[@"content"];
//                      model.updateTime = [responseObject[@"date"] longValue];
//                      model.imgs = responseObject[@"images"];
//                      model.answerCuserId = _cuserId;
//                      [self dismissViewControllerAnimated:YES completion:nil];
//                      if (_finishBlock) {
//                          _finishBlock(model);
//                      }
                  } else if (code == 2) {
                      [MBProgressHUD showErrorMessage:responseObject[@"des"]];
                      BIZLoginViewController *vc = [BIZLoginViewController viewControllerFromStoryboard];
                      [self presentViewController:vc animated:YES completion:nil];
                  } else {
                      [MBProgressHUD showErrorMessage:responseObject[@"des"]];
                  }
                  
                  
              }
              failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                  if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
                      [MBProgressHUD showErrorMessage:@"网络不给力"];
                  }
                  else {
                      [MBProgressHUD showErrorMessage:@"服务器繁忙"];
                  }
                  
              }
     ];

}

@end
